package cn.lyw.init;

import cn.common.beancopy.util.BeanCopierUtil;
import cn.common.init.InitDataConstant;
import cn.common.redis.RedisServie;
import cn.common.restresult.util.RestResult;
import cn.common.restresult.util.ResultEnum;
import cn.lyw.seckillgoods.mapper.pojo.SmallMiSeckillGoods;
import cn.lyw.seckillgoods.service.bo.EditSeckillGoodsBO;
import cn.lyw.seckillgoods.service.bo.GetSeckillGoodsBySessionBO;
import cn.lyw.seckillgoods.service.domain.GetSeckillGoodsBySessionDO;
import cn.lyw.seckillgoods.service.service.SeckillGoodsService;
import cn.lyw.seckillsession.service.bo.EditSessionBO;
import cn.lyw.seckillsession.service.domain.GetSessionByIdDO;
import cn.lyw.seckillsession.service.service.SeckillSessionService;
import com.fasterxml.jackson.databind.ser.Serializers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @Author   lyw
 * @Description 监听redis过期key
 * @Date 12:04 2021/7/20
 * @Param
 * @return
 */
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }


    @Autowired
    private SeckillSessionService seckillSessionService;

    @Autowired
    private SeckillGoodsService seckillGoodsService;

    @Autowired
    private RedisServie redisServie;

    /**
     * @Author   lyw
     * @Description 针对 redis 数据失效事件，进行数据处理
     * @Date 12:04 2021/7/20
     * @Param
     * @return
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {

        // 获取到失效的 key
        String expiredKey = message.toString();
        //通过：截取字符串
        String[] split = expiredKey.split(":");
        System.out.println(expiredKey);

        /**如果是未开始的秒杀场次过期，就添加到活动中的redis中，
        并修改数据库的状态，以及查询这个场次的商品，存入redis中*/
        if (split[2].equals("seckillNotStart")){

            //根据返回的场次id查询信息
            GetSessionByIdDO sessionById = seckillSessionService.getSessionById(split[3]);

            EditSessionBO editSessionBO = new EditSessionBO();
            editSessionBO.setSessionId(sessionById.getSessionId());
            editSessionBO.setVersion(sessionById.getVersion());
            editSessionBO.setSessionState("seckillActivity");

            //修改
            RestResult restResult = seckillSessionService.editSession(editSessionBO);

            if (restResult.getCode().equals(ResultEnum.EDIT_ERROR.code)){
                System.out.println("错了");
            }

            //查询修改后商品
            GetSessionByIdDO sessionById1 = seckillSessionService.getSessionById(split[3]);

            //获取时间
            long time = sessionById1.getEndTime().getTime();
            long time1 = (new Date()).getTime();
            long l = (time - time1)/1000;

            //存入redis
            redisServie.putHash(InitDataConstant.SECKILL_SESSION_SECKILLACTIVITY+sessionById1.getSessionId(),sessionById1.getSessionId(),sessionById1,l);

            //根据场次id查询秒杀商品
            GetSeckillGoodsBySessionBO getSeckillGoodsBySessionBO = new GetSeckillGoodsBySessionBO();
            getSeckillGoodsBySessionBO.setSeckillSessionId(split[3]);

            List<GetSeckillGoodsBySessionDO> seckillGoodsBySession = seckillGoodsService.getSeckillGoodsBySession(getSeckillGoodsBySessionBO);

            //存入redis
            redisServie.setList(InitDataConstant.SECKILL_GOODS+split[3],seckillGoodsBySession);

        }


        //活动中的
        if (split[2].equals("seckillActivity")){

            //根据返回的场次id查询信息
            GetSessionByIdDO sessionById = seckillSessionService.getSessionById(split[3]);

            EditSessionBO editSessionBO = new EditSessionBO();
            editSessionBO.setSessionId(sessionById.getSessionId());
            editSessionBO.setVersion(sessionById.getVersion());
            editSessionBO.setSessionState("seckillFinished");

            //修改场次
            RestResult restResult = seckillSessionService.editSession(editSessionBO);

            if (restResult.getCode().equals(ResultEnum.EDIT_ERROR.code)){
                System.out.println("错了");
                return;

            }

            //将redis中的商品同步到数据库
            List<SmallMiSeckillGoods> list = redisServie.getList(InitDataConstant.SECKILL_GOODS + split[3], SmallMiSeckillGoods.class);

            for (SmallMiSeckillGoods smallMiSeckillGoods : list) {

                //转换类型
                EditSeckillGoodsBO editSeckillGoodsBO = BeanCopierUtil.copyObj(smallMiSeckillGoods, EditSeckillGoodsBO.class);

                //修改商品
                RestResult restResult1 = seckillGoodsService.editSeckillGoods(editSeckillGoodsBO);

                if (restResult1.getCode().equals(ResultEnum.EDIT_ERROR.code)){
                    System.out.println("又错了");
                    return;
                }

            }

            //同步完成后，删除redis中的数据
            redisServie.delete(InitDataConstant.SECKILL_GOODS + split[3]);

        }


    }

}
